package com.example.demo.provider;

import com.alibaba.fastjson.JSON;
import com.example.demo.dto.AccessTokenDTO;

import com.example.demo.dto.GiteeUser;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Component
public class GiteeProvoder {
    public String getAccessToken(AccessTokenDTO accessTokenDTO) throws IOException {

        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
        Request request = new Request.Builder()
                .url("https://gitee.com/oauth/token?grant_type=authorization_code")
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String string  = response.body().string();
            HashMap Map = JSON.parseObject(string, HashMap.class);
            String key=Map.get("access_token").toString();
            return  key;
        } catch (IOException e) {
            return null;
        }
    }

    public GiteeUser giteeUser(String accessToken) throws IOException {
            OkHttpClient client1 = new OkHttpClient();
            Request request1 = new Request.Builder()
                    .url("https://gitee.com/api/v5/user?access_token="+accessToken)
                    .build();
            Response response = client1.newCall(request1).execute();
            String string=response.body().string();
            GiteeUser giteeUser1=com.alibaba.fastjson.JSON.parseObject(string,GiteeUser.class);
            return  giteeUser1;

    }
}
